package com.example.esc_im_client.ui.home;

import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.esc_im_client.rpc.RpcDemoClient;
import android.view.View;
import android.widget.LinearLayout;
import com.example.esc_im_client.rpc.request.LgCollectAddtoolJsonPostReq;
import androidx.appcompat.app.AppCompatActivity;
import com.mpaas.mgs.adapter.api.MPRpc;
import com.alipay.mobile.antcube.CubeService;
import com.antfin.cube.antcrystal.api.CCardCallback;
import com.antfin.cube.antcrystal.api.CCardType;
import com.antfin.cube.antcrystal.api.CubeCard;
import com.antfin.cube.antcrystal.api.CubeCardConfig;
import com.antfin.cube.antcrystal.api.CubeCardResultCode;
import com.antfin.cube.antcrystal.api.CubeView;
import com.antfin.cube.platform.systeminfo.MFSystemInfo;
import com.alipay.mobile.common.rpc.RpcException;
import com.example.esc_im_client.R;
import com.example.esc_im_client.rpc.model.home_request;
import com.mpaas.mas.adapter.api.MPLogger;
import android.util.Log;
public class FastActivity extends AppCompatActivity {

    private static final String TAG = "FastActivity";

    private CubeCard mCard;
    private LinearLayout mWrapperLl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        mWrapperLl = findViewById(R.id.cube_wrapper);
        requestCubeCard(assembleCubeCardConfig());
        //原生跳卡片传参
        findViewById(R.id.js_click_to_cube).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCard != null) {
                    mCard.callJsFunction("clientToCube",JSON.parseObject("{\"vipInfo\":{\"expireTime\":\"1532599846111\",\"level\":\"101\"},\"name\":\"alipay TestCase\",\"age\":\"20\"}"));
                }
            }
        });

        homeRpc();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCubeCard();
    }

    /**
     * 组装卡片配置信息
     *
     * @return
     */
    private CubeCardConfig assembleCubeCardConfig() {
        // 创建卡片配置
        CubeCardConfig cardConfig = new CubeCardConfig();
        // 后台创建的卡片ID
        cardConfig.setTemplateId("demo00001");
        // 卡片版本
        cardConfig.setVersion("0.0.0.7");
        // 卡片宽度，这里选取屏幕宽度
        cardConfig.setWidth(MFSystemInfo.getPortraitScreenWidth());
        return cardConfig;
    }

    /**
     * 请求卡片信息
     *
     * @param cardConfig
     */
    private void requestCubeCard(final CubeCardConfig cardConfig) {
        // 创建卡片信息
        CubeService.instance().getEngine().createCard(cardConfig, new CCardCallback() {
            @Override
            public void onLoaded(final CubeCard cubeCard, CCardType cardType, CubeCardConfig cubeCardConfig, CubeCardResultCode resultCode) {
                renderCubeCard(cubeCard, cardType, cubeCardConfig, resultCode);
            }
        });
    }

    /**
     * 渲染卡片
     *
     * @param cubeCard
     * @param cardType
     * @param cubeCardConfig
     * @param resultCode
     */
    private void renderCubeCard(final CubeCard cubeCard, CCardType cardType, CubeCardConfig cubeCardConfig, CubeCardResultCode resultCode) {
        if (resultCode == CubeCardResultCode.CubeCardResultSucc) {
            // 需要运行在主线程
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCard = cubeCard;
                    // 创建卡片View
                    CubeView view = CubeService.instance().getEngine().createView(FastActivity.this);
                    // 添加到外层 ViewGroup 里
                    mWrapperLl.addView(view);
                    // 渲染卡片
                    cubeCard.renderView(view);
                }
            });
            MPLogger.info(TAG, "succ " + cubeCardConfig.getTemplateId() + " style " + cardType);
        } else {
            MPLogger.info(TAG, "fail " + cubeCardConfig.getTemplateId() + " style " + cardType + " error " + resultCode);
        }
    }

    /**
     * 释放卡片资源
     */
    private void releaseCubeCard() {
        if (mCard != null) {
            mCard.recycle();
        }
        int chidrenCount = mWrapperLl.getChildCount();
        for (int i = 0; i < chidrenCount; i++) {
            if (mWrapperLl.getChildAt(i) instanceof CubeView) {
                ((CubeView) mWrapperLl.getChildAt(i)).destroy();
            }
        }
        mWrapperLl.removeAllViews();
    }

    public void homeRpc(){
       new Thread(new Runnable() {
           @Override
           public void run() {
               // 获取 client 实例
               RpcDemoClient client = MPRpc.getRpcProxy(RpcDemoClient.class);
                // 设置请求
               LgCollectAddtoolJsonPostReq req = new LgCollectAddtoolJsonPostReq();
               home_request home = new home_request();
               home.type = "123";
               home.page = "14";
               req._requestBody = home;

                // 发起 RPC 请求
               try {
                   String response = client.lgCollectAddtoolJsonPost(req);
                   Log.i("RPC反参", response);
                   if (mCard != null) {
                       mCard.callJsFunction("clientToCube", JSON.parseObject(response));
                   }
               } catch (RpcException e) {
                   // 处理 RPC 请求异常
                   Log.i("RpcException", "code: " + e.getCode() + " msg: " + e.getMsg());
               }
           }
       }).start();

    }
}